<template>
  <div class="p-[16px] bg-[var(--base-color)] flex" style="height: calc(100% - 8px); flex-direction: column">
    <div class="text-[14px] leading-[20px] font-[400] w-[100%] flex items-center flex">
      <div class="font-[600] mr-[15px]">订单利润</div>
      <div>结算状态：{{ settlementStatusDesc || "--" }}</div>

      <span class="ml-[15px]" v-if="settlement_time">结算时间：{{ settlement_time || "--" }}</span>
      <span class="ml-[15px]">更新时间：{{ profit_time || "--" }}</span>
      <el-checkbox v-model="tag" true-value="v2" false-value="v1" class="ml-auto w-[140px]">财务接口V2</el-checkbox>
    </div>
    <div class="flex justify-between">
      <div class="">
        <div
          class="text-[14px] leading-[20px] mr-[20px] inline-block"
          v-for="item in orderConfig"
          :key="item.label"
          :class="['profit_rate', 'sales_gross_rate'].includes(item.field) ? 'font-[600]' : ''"
        >
          <div v-if="item.field == 'profit'">{{ item.label }}: {{ formData.profit }} RMB / {{ ((formData?.profit || 0) / formData?.exchange_rate)?.toFixed(2) }} {{ formData.order_currency }}</div>

          <div v-else>{{ item.label }}: {{ formData[item.field] }} {{ ["profit_rate", "sales_gross_rate"].includes(item.field) ? "%" : "" }}</div>
        </div>

        <VXSelect dictionary="expense_stage" style="width: 100px" placeholder="订单状态" @change="handleChangeOrderStatus" v-model="orderStatus" />
        <el-select v-model="currency" placeholder="费用币种" class="ml-[12px]" style="width: 100px" @change="updateFooter">
          <el-option v-for="val in currencyOpt" :label="val" :value="val" :key="val" />
        </el-select>
      </div>
      <div class="w-[280px] min-w-[280px]">
        <el-button @click="handleOpera(1)">刷新页面内容</el-button>
        <el-button type="primary" @click="handleOpera(2)">重新计算利润</el-button>
      </div>
    </div>
    <div class="flex-1 flex" style="flex-direction: column">
      <VTable ref="tableRef" v-bind="tableOptions" class="table-view">
        <template #HeaderContent="{ column }">
          {{ column.title }}
          <div>{{ column.field == "profit_scale" ? "" : currency }}</div>
        </template>
        <template #DefaultContent="{ row, column }">
          {{ currency == "RMB" ? row[column.field]?.toFixed(2) : (Number(row[column.field]) / Number(formData.exchange_rate))?.toFixed(2) }}
        </template>
      </VTable>

      <div class="text-right p-[6px] flex-1">
        <div>
          利润 :
          <span class="font-[500] text-[18px]">
            RMB <span class="text-blue text-[22px]">{{ formData?.profit }}</span> / {{ formData.order_currency || "-" }}
            <span class="text-blue text-[22px]">{{ ((formData?.profit || 0) / formData?.exchange_rate)?.toFixed(2) }}</span>
          </span>
        </div>
        <div>
          利润率
          <span class="font-[500] text-[18px]">
            <span class="text-red text-[22px]">{{ formData?.profit_rate }}%</span>
          </span>
        </div>
      </div>
    </div>

     
  </div>
</template>

<script setup lang="jsx">
import req from "@/views/user/list/add/api/index"
import { ElMessage } from "element-plus"
const tableRef = ref()
const params = ref({})

const props = defineProps({
  api: { type: Function, default: () => [] },
})

const formData = ref({})
// 订单状态
const orderStatus = ref("")
const orderList = ref([])
const settlementStatusDesc = ref("")
const profit_time = ref("")
const settlement_time = ref("")
const router = useRouter()
const { id } = router.currentRoute.value.query || {}

const currency = ref("RMB")
const currencyOpt = ref(["RMB"])
const tag = ref("v1")

const orderConfig = ref([
  { label: "平台订单号", field: "platform_order_sn" },
  { label: "系统订单号", field: "order_sn" },
  { label: "汇率", field: "exchange_rate" },
  { label: "订单利润", field: "profit" },
  { label: "订单利润率", field: "profit_rate" },
  { label: "销售毛利率", field: "sales_gross_rate" },
])

const { api } = toRefs(props)

const handleOpera = (type) => {
  const dtd = { orderIds: [id] }
  if (type === 1) {
    currency.value = "RMB"
    tableRef.value.query()
  } else {
    req.againCalculate(dtd)
  }
  ElMessage.success("操作成功！")
}
const headerCellStyle = ({ row, column }) => {
  if (column.title == "收入") {
    return { background: "var(--base-primary-dark-bg)!important", color: "#fff" }
  }
  if (column.title == "支出") {
    return { background: "var(--base-danger-dark-bg)!important", color: "#fff" }
  }
}

const tableOptions = reactive({
  height: null,
  minHeight: "0px",
  maxHeight: "500px",
  showOverflow: true,
  border: "full",
  pagerConfig: { pageSize: 10 },
  align: "center",
  round: true,
  headerCellStyle: headerCellStyle,
  footerCellStyle: () => {
    return { height: "62px" }
  },

  rowConfig: { height: 62 },
  columnConfig: { resizable: true },
  // 尾行计算
  showFooter: true,
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return "总利润"
        }
        // 利润率
        if (column.field == "profit_scale") {
          return formData.value.profit_rate || "-" + "%"
        }
        // 利润
        if (column.field == "profit") {
          let profit = 0
          profit = eval(data.map((v) => v[column.field] || 0).join("+"))
          profit = currency.value == "RMB" ? profit?.toFixed(2) : (profit / formData.value.exchange_rate)?.toFixed(2)
          return profit
        }

        if (currency.value == "RMB") {
          return eval(data.map((v) => v[column.field] || 0).join("+"))?.toFixed(2)
        } else {
          return (eval(data.map((v) => v[column.field] || 0).join("+")) / formData.value.exchange_rate)?.toFixed(2)
        }
      }),
    ]
  },

  columns: [
    {
      title: "",
      children: [
        {
          field: "order_sn",
          title: `平台订单号`,
          align: "left",
          width: 208,
          slots: {
            header: ({ row }) => {
              return `平台订单号\n${formData.value.platform_order_sn || ""}`
            },
            default: ({ row }) => (
              <div>
                <div>
                  {row.receipt_type_desc}
                  {row.order_sn == formData.order_sn ? "(当前单)" : ""}
                  {row.stage == 1 ? "(预估)" : "(真实)"}
                </div>
                <div>{row.order_sn}</div>
              </div>
            ),
          },
        },
      ],
    },

    {
      title: "收入",
      children: [
        {
          title: `产品销售收入`,
          field: "sales_revenue",
          width: 120,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },
        {
          title: `运费收入`,
          field: "freight_revenue",
          width: 84,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },
        {
          title: `退款金额`,
          field: "refund_revenue",
          width: 84,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },
        {
          title: `优惠金额`,
          field: "discount_amount",
          width: 84,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },
        {
          title: `其他收入`,
          field: "other_revenue",
          width: 84,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },
        {
          title: `税费收入`,
          field: "tax_revenue",
          width: 84,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },
        {
          title: `扣除客户税费`,
          field: "deduct_customer_tax",
          width: 120,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },
      ],
    },
    {
      title: "支出",
      children: [
        {
          title: `交易佣金`,
          field: "trade_commission",
          width: 84,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },

        {
          title: `采购成本`,
          field: "purchase_cost",
          width: 84,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },
        {
          title: `小包/海外尾程运费`,
          field: `overseas_warehouse_freight`,
          width: 154,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },
        {
          title: `头程运费`,
          field: "head_trip_freight",
          width: 84,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },
        {
          title: `关税`,
          field: "tariff",
          width: 84,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },
        {
          title: `海外仓入库费`,
          field: "overseas_warehousing_fee",
          width: 114,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },

        {
          title: `平台/海外仓操作费`,
          children: [
            { title: `FBA操作费`, field: "fba_operate_fee", width: 104, slots: { default: "DefaultContent" } },
            { title: `海外仓操作费`, field: "overseas_warehouse_operate_fee", width: 118, slots: { default: "DefaultContent" } },
          ],
        },
        {
          title: `平台其他支出`,
          field: "other_platform_expenses",
          width: 114,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },
        {
          title: `包装成本`,
          field: "package_cost",
          width: 114,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },
        {
          title: `自定义费用（仓库管理成本）`,
          field: "custom_expense_items",
          width: 240,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },

        {
          title: `自定义费用（其他费用成本）`,
          field: "custom_expense_items_other",
          width: 240,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },

        {
          title: `自定义导入费用`,
          field: "custom_import_items",
          width: 130,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },
        {
          title: `预设运营费用`,
          field: "operate_cost",
          width: 120,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },
        {
          title: `广告费`,
          field: `advertise_fee`,
          width: 100,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },
      ],
    },

    {
      title: "",
      children: [
        {
          title: `利润`,
          field: "profit",
          fixed: "right",
          width: 90,
          slots: { header: "HeaderContent", default: "DefaultContent" },
        },
        {
          title: `利润率`,
          field: "profit_scale",
          fixed: "right",
          width: 84,
          slots: {
            default: ({ row }) => {
              return `${row?.profit_scale || "-"}%`
            },
          },
        },
      ],
    },
  ],
  pagerConfig: {
    enabled: false,
    autoHidden: true,
  },
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    ajax: {
      query: ({ page }) => {
        return getData()
      },
    },
  },
})

const getData = async () => {
  const res = await req.ofeeList({ id: id, stage: orderStatus.value, tag: tag.value })
  // const res = await req.ofeeList({ id: id, stage: orderStatus.value })
  orderStatus.value = res.data.stage
  formData.value = res.data
  // 币种
  currencyOpt.value = ["RMB", res.data.order_currency]
  res.data.orders?.forEach((item) => {
    item.overseas_warehouse_freight = item.overseas_warehouse_freight || item.local_warehouse_freight || 0
  })

  orderList.value = res.data.orders || []
  settlementStatusDesc.value = res.data.settlement_status_desc
  profit_time.value = res.data.profit_time
  settlement_time.value = res.data.settlement_time
  updateFooter()
  return orderList.value || []
}
// 重新计算合计行
const updateFooter = () => {
  nextTick(() => tableRef.value.$table.updateFooter())
}
const handleChangeOrderStatus = (value) => {
  tableRef.value.query()
}

onMounted(() => {})
</script>
<style lang="scss" scoped>
.page-wrap {
  .table-view {
    flex: 1;
    :deep(thead .vxe-header--row:nth-child(1) .vxe-header--column) {
      padding: 14px 0;
      background-color: var(--base-table-header-bg-color) !important;
    }
    :deep(.vxe-header--column) {
      background-color: var(--base-table-header-bg-color) !important;
    }
  }
}
</style>
